import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { authService } from '@/services/auth.service'

interface User {
  id: string
  email: string
  username?: string
  name?: string
  role: string
  avatar?: string
  createdAt: string
  updatedAt: string
}

interface UserState {
  user: User | null
  token: string | null
  isLoading: boolean
  error: string | null

  // Actions
  setUser: (user: User) => void
  setToken: (token: string) => void
  login: (email: string, password: string, remember?: boolean) => Promise<void>
  register: (email: string, username: string, password: string) => Promise<void>
  logout: () => Promise<void>
  updateProfile: (data: Partial<User>) => Promise<void>
  clearError: () => void
  clearAllData: () => void // 新增：完全清除所有数据
}

export const useUserStore = create<UserState>()(
  devtools(
    persist(
      (set, get) => ({
        user: null,
        token: null,
        isLoading: false,
        error: null,
        
        setUser: (user) => set({ user }),
        
        setToken: (token) => set({ token }),
        
        login: async (email, password, remember = false) => {
          set({ isLoading: true, error: null })
          
          try {
            const data = await authService.login(email, password, remember)
            
            set({
              user: data.user,
              token: data.token,
              isLoading: false
            })
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '登录失败',
              isLoading: false
            })
            throw error
          }
        },
        
        register: async (email, username, password) => {
          set({ isLoading: true, error: null })
          
          try {
            const data = await authService.register({ email, username, password })
            
            // After successful registration, auto-login
            await get().login(email, password)
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : '注册失败',
              isLoading: false
            })
            throw error
          }
        },
        
        logout: async () => {
          try {
            await authService.logout()
          } finally {
            set({ user: null, token: null })
          }
        },
        
        updateProfile: async (data) => {
          const user = get().user
          const token = get().token
          
          if (!user || !token) {
            throw new Error('User not authenticated')
          }
          
          set({ isLoading: true, error: null })
          
          try {
            // TODO: Replace with actual API call
            const response = await fetch(`${import.meta.env.VITE_API_URL || '/api/v1'}/users/${user.id}`, {
              method: 'PUT',
              headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
              },
              body: JSON.stringify(data)
            })
            
            if (!response.ok) {
              throw new Error('Update failed')
            }
            
            const updatedUser = await response.json()
            
            set({
              user: updatedUser,
              isLoading: false
            })
          } catch (error) {
            set({
              error: error instanceof Error ? error.message : 'Update failed',
              isLoading: false
            })
            throw error
          }
        },
        
        clearError: () => set({ error: null }),

        clearAllData: () => {
          // 清除 store 数据
          set({ user: null, token: null, error: null })
          // 清除 localStorage
          localStorage.removeItem('user-storage')
        }
      }),
      {
        name: 'user-storage',
        partialize: (state) => ({
          user: state.user,
          token: state.token
        })
      }
    ),
    {
      name: 'UserStore'
    }
  )
)